import requests
import datetime
import os


class webhookSenderAndLogger:
    def __init__(self):
        pass

    def send_and_log(self, webhook_url, title, at, text, title_color):
        global response
        data = {
            "msg_type": "interactive",
            "card": {
                "elements": [
                    {
                        "tag": "div",
                        "text": {
                            "content": f"<at id={at}></at>\n{text}",
                            "tag": "lark_md"
                        }
                    }
                ],
                "header": {
                    "template": title_color,
                    "title": {
                        "content": title,
                        "tag": "plain_text"
                    }
                }
            }
        }

        now = datetime.datetime.now()
        post_time = now.strftime("%Y-%m-%d %H:%M:%S")

        try:
            response = requests.post(webhook_url, json=data)

            today = datetime.date.today().strftime("%Y-%m-%d")
            log_file = f"./log/{today}.log"

            if not os.path.exists(f"./log"):
                os.makedirs(f"./log")

            with open(log_file, "a") as f:
                f.write(f"发送时间: {post_time}\n")
                f.write(f"机器人对应地址: {webhook_url}\n")
                f.write(f"发送参数: {data}\n")
                f.write(f"返回结果: {response.text}\n")
                f.write("\n")

            if response.json()["msg"] == "success":
                return "success"
            else:
                return "fail"

        except requests.exceptions.RequestException as e:
            # 在这里处理请求异常的情况，比如返回特定的提示信息
            print("请求出错:", response.text)
            print("请求出错:", e)
            return "error"
